package com.hjk.common.aop.aspect;

import com.hjk.common.aop.annotation.NotCheckToken;
import com.hjk.common.model.SystemTokenQo;
import com.hjk.common.response.enums.ErrorCodeEnum;
import com.hjk.common.response.exception.BaseException;
import com.hjk.common.utils.aop.AopUtils;
import com.hjk.common.utils.check.Check;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * token和syscode校验类
 *
 * @author huangjunkai
 * @version 1.0
 * @date 2020/9/9 9:33
 */
@Aspect
@Component
public class CheckTokenAspect {



    private static final Logger log = LoggerFactory.getLogger(CheckTokenAspect.class);

    @Pointcut("execution(public * com.hjk.*.*.StandardPayController.*(..))  || @annotation(com.hjk.common.aop.annotation.CheckToken) ")
    private void standardPay() {
    }

    @Around("standardPay()")
    public Object doAround(ProceedingJoinPoint pjp) throws Throwable {
        //存在NotCheckToken注解 不校验 必填参数(系统编码||请求token)
        if (Check.isNotEmpty(AopUtils.getAnnotation(pjp, NotCheckToken.class))) {
            return pjp.proceed();
        }

        String fullMethodName = AopUtils.getFullMethodName(pjp);
        //请求的参数
        Object[] args = pjp.getArgs();
        //SystemTokenQo systemTokenQo = (SystemTokenQo) args[0];
        SystemTokenQo systemTokenQo = (SystemTokenQo) Arrays.stream(args).filter(f -> f instanceof SystemTokenQo).findFirst().orElse(null);
        if (Check.isEmpty(systemTokenQo)) {
            return new BaseException(ErrorCodeEnum.GL99990401);
        }

        String syscode = systemTokenQo.getSyscode();
        String token = systemTokenQo.getToken();
        log.debug("[标准缴费], fullMethodName: {}, standardPayQoJson: {}", fullMethodName, systemTokenQo);

        //校验请求对象
        if (Check.isEmpty(systemTokenQo)) {
            return new BaseException(ErrorCodeEnum.GL99990401);
        }

        //校验必填参数 ( 系统编码  请求token)
        if (Check.isEmpty(syscode) || Check.isEmpty(token)) {
            return new BaseException(ErrorCodeEnum.GL99990401);
        }

        //校验必填参数 ( 系统编码  请求token)
        //1.根据sysCode查询是否存在tokenStr
       // String tokenStr = standardPaySystemTokenDao.getTokenStrBySysCode(syscode);
        //if (Check.isEmpty(tokenStr)) {
       //     return new BaseException(StandardPayConstant.SYSCODE_ERROR);
       // }

       // String timeToken = TokenUtils.getCurrentTimeToken(tokenStr);
        String timeToken = "";
        log.debug("数据库生成的 " + timeToken);
        log.debug("请求的 " + token);
        if (!timeToken.equalsIgnoreCase(token)) {
            return new BaseException(ErrorCodeEnum.GL99990401);
        }

        //执行方法
        return pjp.proceed();
    }


}
